<script setup lang="ts">
import { useRole } from "./utils/hook";
import {
  ref,
  computed,
  nextTick,
  h,
  onMounted,
  defineAsyncComponent
} from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import useProComponent from "@/composables/useProComponent";
import multiple from "../multiple/index.vue";
import ReDrawer from "@/components/ReDrawer";
import ReDialogOrDrawer from "@/components/ReDialogOrDrawer";
import {
  delay,
  subBefore,
  deviceDetection,
  useResizeObserver
} from "@pureadmin/utils";

import EditPen from "@iconify-icons/ep/edit-pen";
import Refresh from "@iconify-icons/ep/refresh";
import AddFill from "@iconify-icons/ri/add-circle-line";
import Install from "@iconify-icons/ri/install-line";

defineOptions({
  name: "SystemRole"
});

const iconClass = computed(() => {
  return [
    "w-[22px]",
    "h-[22px]",
    "flex",
    "justify-center",
    "items-center",
    "outline-none",
    "rounded-[4px]",
    "cursor-pointer",
    "transition-colors",
    "hover:bg-[#0000000f]",
    "dark:hover:bg-[#ffffff1f]",
    "dark:hover:text-[#ffffffd9]"
  ];
});
const { openComponent } = useProComponent();

const treeRef = ref();
const formRef = ref();
const tableRef = ref();
const contentRef = ref();
const treeHeight = ref();

const handleOpenProComponent = () => {
  openComponent({
    componentType: "dialog", // 指定类型为 drawer 或 dialog
    title: "增强版 ProComponent", // 弹窗标题
    formModel: {
      name: "",
      status: "1",
      rate: 4,
      progress: 100,
      switch: true,
      time: new Date().toString(),
      endTime: []
    },
    formSchema: [
      {
        label: "名称",
        width: 120,
        prop: "name",
        valueType: "copy",
        tooltip: "我是名称"
      },
      {
        label: "状态",
        width: 120,
        prop: "status",
        valueType: "select",
        options: [
          { label: "未解决", value: "0", color: "red" },
          { label: "已解决", value: "1", color: "blue" },
          { label: "解决中", value: "2", color: "yellow" },
          { label: "失败", value: "3", color: "red" }
        ]
      }
      // 其他表单字段配置...
    ],
    formRules: {
      name: [{ required: true, message: "请输入名称", trigger: "blur" }]
    },
    beforeSubmit: async formModel => {
      console.log("Before Submit:", formModel);
      return true;
    },
    onSubmit: formModel => {
      console.log("Submitted data:", formModel);
    },
    onSubmitError: errors => {
      console.log("Submit errors:", errors);
    },

    componentProps: {
      // 传递给 ElDialog 的额外属性
      width: "60%", // 设置弹窗宽度
      center: true, // 内容居中显示
      appendToBody: true, // 弹窗附加到 body 元素
      draggable: true, // 允许拖拽对话框
      showClose: true, // 显示关闭按钮
      beforeClose: done => {
        // 在关闭前执行一些逻辑
        console.log("即将关闭对话框");
        done(); // 调用 done() 关闭对话框
      }
    }
  });
};

const formModel = ref({
  lists: []
});

const isVisible = ref(false); // 控制弹窗的显示和隐藏
const handleOpenDialog = () => {
  isVisible.value = true;
};

const handleFormSubmit = submittedFormModel => {
  console.log("表单提交:", submittedFormModel);
};

const handleFormClose = () => {
  console.log("弹窗已关闭");
};

const {
  form,
  isShow,
  loading,
  columns,
  dataList,
  pagination,
  onSearch,
  resetForm,
  openDialog,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange
} = useRole(treeRef);

onMounted(() => {
  useResizeObserver(contentRef, async () => {
    await nextTick();
    delay(60).then(() => {
      treeHeight.value = parseFloat(
        subBefore(tableRef.value.getTableDoms().tableWrapper.style.height, "px")
      );
    });
  });
});
</script>

<template>
  <div class="main">
    <ReDialogOrDrawer
      v-model:visible="isVisible"
      :title="'自定义弹窗'"
      :component-type="'dialog'"
      :form-model="formModel"
      :custom-content="multiple"
      @submit="handleFormSubmit"
      @close="handleFormClose"
    />
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item label="表名称：" prop="table_name">
        <el-input
          v-model="form.table_name"
          placeholder="请输入表名称"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <div
      ref="contentRef"
      :class="['flex', deviceDetection() ? 'flex-wrap' : '']"
    >
      <PureTableBar
        :class="[isShow && !deviceDetection() ? '!w-[60vw]' : 'w-full']"
        style="transition: width 220ms cubic-bezier(0.4, 0, 0.2, 1)"
        title="代码生成"
        :columns="columns"
        @refresh="onSearch"
      >
        <template #title>
          <el-button type="success" :icon="useRenderIcon(Install)"
            >装载数据表</el-button
          >
          <el-button type="primary" @click="handleOpenProComponent"
            >打开增强版抽屉</el-button
          >
          <el-button @click="handleOpenDialog">打开对话框</el-button>
        </template>
        <template #buttons>
          <el-button
            type="primary"
            :icon="useRenderIcon(AddFill)"
            @click="openDialog()"
          >
            新增
          </el-button>
        </template>

        <template v-slot="{ size, dynamicColumns }">
          <!-- <el-button type="primary" plain>Primary</el-button> -->

          <pure-table
            ref="tableRef"
            align-whole="center"
            showOverflowTooltip
            table-layout="auto"
            :loading="loading"
            :size="size"
            adaptive
            :adaptiveConfig="{ offsetBottom: 108 }"
            :data="dataList"
            :columns="dynamicColumns"
            :pagination="pagination"
            :paginationSmall="size === 'small' ? true : false"
            :header-cell-style="{
              background: 'var(--el-fill-color-light)',
              color: 'var(--el-text-color-primary)'
            }"
            @selection-change="handleSelectionChange"
            @page-size-change="handleSizeChange"
            @page-current-change="handleCurrentChange"
          >
            <template #operation="{ row }">
              <el-popconfirm
                :title="`同步会重置字段配置生成信息，确定同步吗?`"
                @confirm="handleSync(row)"
              >
                <template #reference>
                  <el-button
                    class="reset-margin"
                    link
                    type="primary"
                    :size="size"
                    :icon="useRenderIcon(Refresh)"
                  >
                    同步
                  </el-button>
                </template>
              </el-popconfirm>
              <el-button
                class="reset-margin"
                link
                type="primary"
                :size="size"
                :icon="useRenderIcon(EditPen)"
                @click="openDialog('修改', row)"
              >
                修改
              </el-button>
            </template>
          </pure-table>
        </template>
      </PureTableBar>
    </div>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
